package com.tintintech.sendmail.helper;

import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

import org.xbill.DNS.Address;
import org.xbill.DNS.Record;
import org.xbill.DNS.TextParseException;
import org.xbill.DNS.Type;
import org.xbill.DNS.Lookup;
import org.xbill.DNS.MXRecord;

public class DNSHelper {

	public static Record[] getMxRecords(String targetMail)
	{
		Record[] records = {};
		try {
			String server = parse(targetMail);
			if (server == null)
			{
				return null;
			}
			records = new Lookup(server, Type.MX).run();
		} catch (TextParseException tpe) {
			tpe.printStackTrace();
		}
		return records;
	}
	
	/**
	 * 得到目标服务器的IP列表
	 * @param records
	 * @return
	 */
	public static List<String> getTargetServerOfPriority(Record[] records)
	{
		List<String> item = new ArrayList<String>();
		if (records == null)
		{
			return item;
		}
		/* @todo : records 有可能为null */ 
		int i = 0, amount = records.length;
		int p = 0;
		String host = "", high = "";
		// 把优先级最高的放在最前面
		for (; i < amount; i++)
		{
			MXRecord mx = (MXRecord) records[i];
			
			try {
				host = Address.getByName(mx.getTarget().toString()).getHostAddress();
				if (mx.getPriority() > p)
				{
					p = mx.getPriority();
					high = host;
				}
//				item.add(i, host);
				item.add(host);
			} catch (UnknownHostException ukhe) {
				System.out.println("unknown-host");
			}
		}
		if (high != "")
		{
//			item.add(amount, high);
			item.add(high);
		}
		return item;
	}
	
	private static String parse(String targetMail)
	{
		String target = null;
		if (targetMail.indexOf("@") != -1)
		{
			target = targetMail.split("@")[1];
		}
		return target;
	}
}
